import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from firstMainWin import *
import urllib.request
import urllib.parse
import json
import time


class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MyMainWindow, self).__init__()
        self.setupUi(self)
        self.pushButton_2.clicked.connect(self.fan_yi)


    def fan_yi(self):
        while True:
            info=self.textEdit.toPlainText()
            if info == 'B':
                break
            self.url = 'https://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
            self.data = {}
            self.data['i'] = info
            self.data['from'] = 'AUTO'
            self.data['to'] = 'AUTO'
            self.data['smartresult'] = 'dict'
            self.data['client'] = 'fanyideskweb'
            self.data['salt'] = '16262728682943'
            self.data['sign'] = '0bb8f238a3e02796cde41d23dfbb0539'
            self.data['lts'] = '1626272868294'
            self.data['bv'] = 'b0ff5d17f404993192085bf8b1e93587'
            self.data['doctype'] = 'json'
            self.data['version'] = '2.1'
            self.data['keyfrom'] = 'fanyi.web'
            self.data['action'] = 'FY_BY_REALTlME'
            self.data = urllib.parse.urlencode(self.data).encode('UTF-8')
            # 这里用这个方法覆盖原先的data,并且要编码成UTF-8的形式
            self.req = urllib.request.Request(self.url, self.data)
            self.req.add_header('user-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36')
            self.response = urllib.request.urlopen(self.url, self.data)
            self.html = self.response.read().decode('UTF-8')
            # 得到相应之后，注意将其他形式的编码转换为UTF-8的形式
            self.target = json.loads(self.html)
            self.textBrowser.setText(self.target['translateResult'][0][0]['tgt'])
            # print('翻译的结果为：%s' % (target['translateResult'][0][0]['tgt']))
            # 事实上这里的html返回的是一个字典。这样就可以通过字典的访问方式进行访问字典中的内容
            time.sleep(5)
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = MyMainWindow()
    myWin.show()
    sys.exit(app.exec_())